<template>
  <div style="width: 100%; height: 100%">
    <div class="breadcrumb">
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/' }">
          全部文件
        </el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <EmptyFolder v-show="fileList.length === 0 && !loading" />
    <GridFileIcon
      :file-list="fileList"
      :refresh-fn="requests"
      :create-dir-fn="createDir"
      :delete-file-fn="deleteFile"
      :open-file-fn="openFile"
      :rename-file-fn="renameFileFn"
      :move-file-fn="moveFileFn"
      :download-fn="downloadFn"
      :share-fn="showShareFileDialog"
      v-show="watchMode === watchModeType.grid"
    />
    <ListFileIcon
      :file-list="fileList"
      :file-type="fileType"
      :delete-file-fn="deleteFile"
      :open-file-fn="openFile"
      :rename-file-fn="renameFileFn"
      :move-file-fn="moveFileFn"
      :download-fn="downloadFn"
      :share-fn="showShareFileDialog"
      v-show="watchMode === watchModeType.list"
    />
    <el-dialog :visible.sync="dialogVisible">
      <div style="margin-bottom: 20px">
        <span>分享天数</span>
      </div>
      <el-radio v-model="shareDays" label="1">1天</el-radio>
      <el-radio v-model="shareDays" label="7">7天</el-radio>
      <el-radio v-model="shareDays" label="30">1个月</el-radio>
      <el-radio v-model="shareDays" label="-1">永久</el-radio>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="shareFile">
          确 定
        </el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import GridFileIcon from "@/components/GridFileIcon/index";
import { mapGetters, mapActions } from "vuex";
import { newWindow, watchModeType, dialog, ipcMain } from "@/global";
import ListFileIcon from "@/components/ListFileIcon";
import EmptyFolder from "@/components/EmptyFolder/index";
import {
  getFileByDir,
  createDir,
  deleteFile,
  renameFile,
  moveUserFile,
  searchFile,
  copy,
  share
} from "@/api/file";

export default {
  name: "AllFile",
  components: { ListFileIcon, GridFileIcon, EmptyFolder },
  computed: {
    ...mapGetters(["watchMode", "fileType"])
  },
  watch: {
    $route() {
      this.$loading({
        lock: true,
        text: "正在拼命加载中..."
      });
      this.loading = true;
      this.currentDirId = this.$route.query.id;
      getFileByDir(this.$route.query.id).then(res => {
        this.fileList = res.data;
        this.$loading().close();
        this.loading = false;
      });
    }
  },
  methods: {
    requests() {
      this.$loading({
        lock: true,
        text: "正在拼命加载中..."
      });
      this.loading = true;
      getFileByDir(this.currentDirId).then(res => {
        this.fileList = res.data;
        this.$loading().close();
        this.loading = false;
      });
    },
    //路径选择器
    pathSelector(fileId) {
      return new Promise((resolve, reject) => {
        if (this.pathSelectorWin == null) {
          this.pathSelectorWin = newWindow(
            "http://localhost:8080/#pathSelector/" +
              JSON.stringify(this.fileType) +
              "/" +
              fileId
          );
        }
        this.pathSelectorWin.webContents.openDevTools();
        const p = this;
        ipcMain.on("PATH_SELECTOR_CLOSE", (event, args) => {
          if (args === "cancel") {
            reject(args);
          } else {
            resolve(args);
          }
          this.pathSelectorWin.close();
        });
        this.pathSelectorWin.on("closed", () => {
          p.pathSelectorWin = null;
          ipcMain.removeAllListeners("PATH_SELECTOR_CLOSE");
        });
      });
    },
    openFile(file) {
      switch (this.fileType[file.typeId].typeSuffix) {
        case "dir": {
          this.$router.push({ path: "/allFile", query: { id: file.id } });
          break;
        }
        case "mp3":
        case "mp4":
          {
            newWindow("http://localhost:8080/#play/" + file.id);
          }
          break;
        case "jpg":
          {
            newWindow("http://localhost:8080/#view/" + file.id);
          }
          break;
        default: {
          this.$message.info("无法打开未知类型文件");
        }
      }
    },
    createDir() {
      this.$prompt("请输入文件夹名称：", {
        confirmButtonText: "确定",
        cancelButtonText: "取消"
      })
        .then(({ value }) => {
          createDir({ name: value, parentId: this.currentDirId }).then(() => {
            this.$message.success("文件夹创建成功");
            this.requests();
          });
        })
        .catch(err => {
          console.log(err);
        });
    },
    deleteFile(dirId) {
      this.$confirm("真的要删除吗？", {
        confirmButtonText: "确定",
        cancelButtonText: "取消"
      })
        .then(() => {
          deleteFile(dirId).then(() => {
            this.$message.success("删除成功");
            this.requests();
          });
        })
        .catch(err => {
          console.log(err);
        });
    },
    openDialog: async function() {
      await dialog
        .showOpenDialog({
          properties: ["openFile"]
        })
        .then(async res => {
          if (res.canceled === false) {
            const filePath = res.filePaths[0];
            this.$bus.$emit("offerUploadQueue", filePath, this.currentDirId);
          }
        });
    },
    renameFileFn(fileId, name) {
      this.$prompt("请输入新名称：", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        inputValue: name
      })
        .then(({ value }) => {
          renameFile(fileId, value).then(() => {
            this.$message.success("重命名成功");
            this.requests();
          });
        })
        .catch(err => {
          console.log(err);
        });
    },
    async moveFileFn(fileId) {
      const val = await this.pathSelector(fileId);
      const dirId = val === undefined ? null : val;
      moveUserFile(fileId, dirId).then(() => {
        this.requests();
        this.$message.success("文件移动成功");
      });
    },
    downloadFn(fileId, filename) {
      this.$bus.$emit("offerDownloadQueue", fileId, filename);
    },
    showShareFileDialog(fileId) {
      this.shareFileId = fileId;
      this.dialogVisible = true;
    },
    shareFile() {
      share(this.shareFileId, this.shareDays).then(() => {
        this.dialogVisible = false;
        this.$message.success("分享文件成功");
      });
    },
    ...mapActions(["offerUploadQueue"])
  },
  mounted() {
    this.$bus.$on("newDir", () => {
      this.createDir();
    });

    this.$bus.$on("upload", () => {
      this.openDialog();
    });

    this.$bus.$on("refresh", () => {
      this.requests();
    });

    this.$bus.$on("search", keyword => {
      this.$loading({
        lock: true,
        text: "正在拼命加载中..."
      });
      this.loading = true;
      searchFile(keyword)
        .then(res => {
          this.fileList = res.data;
        })
        .finally(() => {
          this.loading = false;
          this.$loading().close();
        });
    });

    this.$bus.$on("copyFile", async fileId => {
      console.log("复制文件");
      const val = await this.pathSelector(fileId);
      const dirId = val === undefined ? null : val;
      copy(fileId, dirId).then(() => this.$message.success("复制文件成功"));
    });

    this.requests();
  },
  destroyed() {
    this.$bus.$off(["newDir", "upload", "refresh", "search"]);
  },
  data() {
    return {
      loading: true,
      watchModeType,
      fileList: [],
      currentDirId: null,
      pathSelectorWin: null,
      dialogVisible: false,
      shareDays: "1",
      shareFileId: null
    };
  }
};
</script>
<style lang="less" scoped>
.breadcrumb {
  padding-bottom: 20px;
}
</style>
